package gui;

import gui.iconos.Icono;

import java.awt.AWTException;
import java.awt.MenuItem;
import java.awt.PopupMenu;
import java.awt.SystemTray;
import java.awt.TrayIcon;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import control.Control;

public class SystemTrayManager {

	private Control control = null;
	private TrayIcon trayIcon = null;
	private PopupMenu popupMenu = null;
	private MenuItem mIMostrar = null;
	private MenuItem mISalir = null;

	public SystemTrayManager(Control control) {

		this.control = control;

		if (SystemTray.isSupported()) {
			SystemTray tray = SystemTray.getSystemTray();
			try {
				tray.add(getTrayIcon());
			} catch (AWTException e) {
				System.out.println("TrayIcon could not be added.");
			}
		} else {
			System.out.println("System tray is currently not supported.");
		}
	}

	private TrayIcon getTrayIcon() {
		if (trayIcon == null) {
			trayIcon = new TrayIcon(Icono.getImagenMain(), "", getMenu());
			trayIcon.setImageAutoSize(true);
			trayIcon.addActionListener(new ActionListener(){
				public void actionPerformed(ActionEvent e){
					control.getGui().setVisible(!control.getGui().isVisible());
				}
			});
		}
		return trayIcon;
	}

	private PopupMenu getMenu() {
		if (popupMenu == null) {
			popupMenu = new PopupMenu();
			popupMenu.add(getMIMostrar());
			popupMenu.addSeparator();
			popupMenu.add(getMISalir());
		}
		return popupMenu;
	}

	private MenuItem getMIMostrar() {
		if (mIMostrar == null) {
			mIMostrar = new MenuItem(getMIMostrarText());
			mIMostrar.addActionListener(new ActionListener() {
				public void actionPerformed(ActionEvent e) {
					control.getGui().setVisible(!control.getGui().isVisible());
					mIMostrar.setLabel(getMIMostrarText());
				}
			});
		}
		return mIMostrar;
	}

	private String getMIMostrarText() {
		if (control.getGui().isVisible()) {
			return "Ocultar";
		}
		return "Mostrar";
	}

	private MenuItem getMISalir() {
		if (mISalir == null) {
			mISalir = new MenuItem("Salir");
			mISalir.addActionListener(new ActionListener() {
				public void actionPerformed(ActionEvent e) {
					control.salir();
				}
			});
		}
		return mISalir;
	}
	
	public void actualizarEstado(){
		getMIMostrar().setLabel(getMIMostrarText());
	}
}
